package rpc

import (
	"context"
	"fmt"
	"github.com/aberic/gnomon"
	"github.com/aberic/gnomon/log"
	proto "gykjgit.dccnet.com.cn/chain/proto/swarm"
	"gykjgit.dccnet.com.cn/chain/swarm/comm"
	"os"
	"path/filepath"
)

type DirServer struct {
}

func (d *DirServer) Sync(_ context.Context, in *proto.ReqDir) (*proto.Response, error) {
	log.Warn("DirServer dirs operation", log.Field("in", in))
	for _, dir := range in.Dirs {
		if dir.IsDir {
			log.Warn("DirServer dirs operation is dir")
			if err := dirs(dir.Operation, dir.FilePath); nil != err {
				return &proto.Response{Code: proto.Code_fail, ErrMsg: err.Error()}, err
			}
		} else {
			log.Warn("DirServer dirs operation is file")
			if err := files(dir.Operation, dir.FilePath, dir.FileName, dir.FileContent); nil != err {
				return &proto.Response{Code: proto.Code_fail, ErrMsg: err.Error()}, err
			}
		}
	}
	return &proto.Response{Code: proto.Code_success}, nil
}

func dirs(operation proto.Operation, path string) error {
	var doPath = gnomon.StringBuildSep(string(filepath.Separator), comm.DirPath, path)
	log.Warn(fmt.Sprintf("dirs operation: %d,filepath: %s", operation, doPath))
	switch operation {
	case proto.Operation_create:
		if gnomon.FilePathExists(doPath) {
			return nil
		}
		return os.MkdirAll(doPath, 0777)
	case proto.Operation_delete:
		if gnomon.FilePathExists(doPath) {
			return os.RemoveAll(doPath)
		}
		return nil
	}
	return nil
}

func files(operation proto.Operation, path, filename, content string) error {
	var doPath = gnomon.StringBuildSep(string(filepath.Separator), comm.DirPath, path)
	var doFilepath = gnomon.StringBuildSep(string(filepath.Separator), doPath, filename)
	log.Warn(fmt.Sprintf("dirs operation: %d,filepath: %s", operation, doPath))
	switch operation {
	case proto.Operation_create:
		_, err := gnomon.FileAppend(doFilepath, []byte(content), true)
		return err
	case proto.Operation_delete:
		if gnomon.FilePathExists(doFilepath) {
			return os.Remove(doFilepath)
		}
		return nil
	}
	return nil
}
